<template>
  <section>
    <!--工具条:高级查询 + 新增店铺-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getShopsByKeyword">查询</el-button>
        </el-form-item>
        <!--<el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>-->
      </el-form>
    </el-col>

    <!--店铺列表-->
    <el-table :data="shops" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="tel" label="电话" width="120">
      </el-table-column>
      <el-table-column prop="address" label="地址" width="200">
      </el-table-column>
      <el-table-column prop="admin.username" label="店长" width="60">
      </el-table-column>
      <el-table-column prop="state" label="店铺状态" width="120" sortable>
        <!-- scope.row当前对象 -->
        <template slot-scope="scope">
          <span style="color: orange" v-if="scope.row.state==0">待审核</span>
          <span style="color: green" v-else-if="scope.row.state==1">审核通过</span>
          <span style="color: red" v-else-if="scope.row.state==-1">驳回</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条:批量删除-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增和编辑对话框或模态框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺电话" prop="tel">
          <el-input v-model="saveForm.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺地址" prop="address">
          <el-input v-model="saveForm.address" auto-complete="off"></el-input>
        </el-form-item>
        <!-- 店铺管理员是在后台加的，前台没有表单项添加 -->
        <el-form-item label="店铺状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="0">待审核</el-radio>
            <el-radio class="radio" :label="1">审核通过</el-radio>
            <el-radio class="radio" :label="-1">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--  点击时隐藏模态框 -->
        <!--@click.native：给vue组件绑定事件时候，必须加上native ，不然不会生效。
        否则会认为监听的是来自Item组件自定义的事件-->
        <!--:loading="saveLoading"：提交按钮忙等框-->
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  //模型数据
  data() {
    return {
      //1.分页查询数据 - 要与模板中对应起来，改了之后报错不用管，改完了再看，因为是全局替换的
      //分页查询 - 分页列表数据
      shops: [],
      //分页查询 - 总数量
      totals: 0,
      //分页查询 - 当前页
      pageSize: 5,
      //分页查询 - 每页显示的条数
      currentPage: 1,
      //列表 - 忙等框
      listLoading: false,

      //2.高级查询 - 关键字查询
      filters: {
        keyword: ''
      },

      //3.批量删除 - 保存被选中对象
      sels: [],//列表选中列


      //4.新增和编辑对话框或模态框的初始化
      saveFormVisible: false,	//对话框是否显示
      saveLoading: false,		//对话框中提交按钮忙等框
      title:"新增",
      saveFormRules: {		//对话框验证规则
        name: [
          //不能为空，失去焦点触发
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入店铺电话', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ]
      },
      //对话框数据初始化
      saveForm: {
        id: null,
        name: null,
        tel: null,
        address: null,
        state: 0
      }
    }
  },

  //定义方法
  methods: {
    //***********//1.分页查询方法 - 获取店铺分页列表数据
    getShops() {
      let params = {
        currentPage: this.currentPage,		//分页查询参数：当前页
        pageSize: this.pageSize,			//分页查询参数：每页显示的数量
        keyword: this.filters.keyword    	//高级查询条件
      };
      //显示忙等框
      this.listLoading = true;
      //发送请求调用店铺分页接口
      this.$http.post("/shop",params).then(res=>{
        //赋值总数量
        this.totals = res.data.totals;
        //赋值分页数据
        this.shops = res.data.data;
        //去掉忙等框
        this.listLoading = false;
      }).catch(res=>{
        alert("系统错误，请稍后重试!");
      })

    },
    //***********//2.点击实现分页查询方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getShops();
    },
    //***********//3.高级查询
    getShopsByKeyword(){
      this.currentPage = 1;
      this.getShops();
    },
    //***********//4.删除操作
    handleDel: function (index, row) {
      //ElementUI的弹框组件：确认框
      this.$confirm('确认删除该记录吗?', '溫馨提示', {
        //警告 - 黄色的 - 删除东西
        type: 'warning'
      }).then(() => {  //确认框点击确认走这里
        //显示忙等框
        this.listLoading = true;
        this.$http.delete("/shop/"+row.id)
            .then(res=>{   //res = AjaxResult对象{"success":true/fasle,"message":"错误提示"}
              //成功不成功都要让盲等框消失
              this.listLoading = false;
              if(res.data.success){//删除成功
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });

                //处理删除最后一页的最后一条数据，回到上一页
                //获取总页数
                //注意Js中：6/5 = 1.2  不是1
                let totalPage = this.totals%this.pageSize==0?Math.floor(this.totals/this.pageSize):Math.floor(this.totals/this.pageSize+1);
                //如果当前页不是第一页，并且当前是最后一页，并且最后页只有一条数据
                if(this.currentPage>1&&this.currentPage==totalPage&&(this.totals-1)%this.pageSize==0){
                  this.currentPage = this.currentPage - 1;
                }

                this.getShops();
              }else{
                //后台500错误，显示具体错误信息
                this.$message.error(res.data.message);
              }
            })
            .catch(res=>{   //res = AjaxResult对象{"success":true/fasle,"message":"错误提示"}
              //主要是针对连接不上服务器啊，前端发送问题等
              this.$message.error("系统错误，请稍后重试!");
            })
      }).catch(() => {   //确认框点击确认走这里
      });
    },
    //***********//5.批量删除 - 批量获取被删除对象的id
    selsChange: function (sels) {
      this.sels = sels;
    },
    //***********//5.批量删除 - 批量删除逻辑处理
    batchRemove: function () {
      //获取被删除对象的id组成的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/shop",ids).then(res=>{
          if(res.data.success){
            this.listLoading = false;
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.currentPage = 1;
            this.getShops();
          }else{
            this.listLoading = false;
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(res=>{
          //主要是针对连接不上服务器啊，前端发送问题等
          this.$message.error("系统错误，请稍后重试!");
        })

      }).catch(() => {
      });
    },

    //***********//6.点击编辑按钮显示编辑界面
    handleEdit: function (index, row) {
      //进行数据回显：将row【本省就是一个json对象  克隆 给一个空对象{}】,防止引用传递导致的数据变化
      this.saveForm = Object.assign({}, row);
      this.title = "编辑";
      //显示模态框
      this.saveFormVisible = true;
    },
    //***********//7.点击添加按钮显示编辑界面
    handleAdd: function () {
      //清空数据
      this.saveForm = {
        id: null,
        name: null,
        tel: null,
        address: null,
        state: 0
      };
      this.title = "新增";
      //显示模态框
      this.saveFormVisible = true;
    },
    //***********//8.点击保存按钮提交模态框的数据到后端
    saveSubmit: function () {
      //表单验证通过之后返回true   valid=true/false
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {
            type: 'info'
          }).then(() => {
            this.saveLoading = true;	//显示提交按钮忙等框
            let para = Object.assign({}, this.saveForm);//克隆数据

            this.$http.put("/shop",para).then(res=>{
              if(res.data.success){
                this.saveLoading = false;
                this.saveFormVisible = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });

                if(!para.id){//如果是添加
                  //获取总页数
                  let totalPage = this.totals%this.pageSize==0?Math.floor(this.totals/this.pageSize):Math.floor(this.totals/this.pageSize+1);
                  //总数量是每页显示的条数的倍数
                  if(this.totals%this.pageSize==0){
                    this.currentPage = totalPage + 1;
                  }else{
                    this.currentPage = totalPage;
                  }
                }

                this.getShops();
              }else{
                this.saveLoading = false;  		//忙等框不显示
                this.saveFormVisible = false; 	//隐藏对话框
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            }).catch(res=>{
              alert("系统错误,请稍后重试");
            })
          });
        }
      });
    }
  },
  //页面一加载就会自动调用mounted函数
  mounted() {
    this.getShops();
  }
}

</script>

<style scoped>

</style>